import os
import sys
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-1%#bhl&e!5(kmoj6zl5fcc6^$n^vyqhw=m_xcd7b+62r0saqeh'

DEBUG = False

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOST', '*').split(',')

# Application definition
INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework_jwt',
    'django_apscheduler',
    "user.apps.UserConfig",
    "role.apps.RoleConfig",
    "menu.apps.MenuConfig",
    'corsheaders',
    "hosts_mgr.apps.HostsMgrConfig",
    "channels",
    "monitor_alert_center.apps.MonitorAlarmCenterConfig",
    "dashboard.apps.DashboardConfig",
    'addcomments',
    'drf_yasg',
    'guacamole',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'user.middleware.JwtAuthenticationMiddleware',
]

ROOT_URLCONF = 'BroadviewCoss.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'BroadviewCoss.wsgi.application'

ASGI_APPLICATION = 'BroadviewCoss.asgi.application'

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# 邮件发送方邮箱地址：
EMAIL_SENDER = os.environ.get('EMAIL_SENDER', '123@163.com')
# 邮件发送方邮箱密码：
EMAIL_PASSWD = os.environ.get('EMAIL_PASSWD', 'XXX')
EMAIL_SERVER = os.environ.get('EMAIL_SERVER', 'smtp.163.com')
EMAIL_SERVER_PORT = os.environ.get('EMAIL_SERVER_PORT', 994)

DB_NAME = os.environ.get('DB_NAME', 'broadview_coss')
DB_USER = os.environ.get('DB_USER', 'root')
DB_PASSWORD = os.environ.get('DB_PASSWORD', '@21cn.co')
DB_PORT = os.environ.get('DB_PORT', '3307')
DB_HOST = os.environ.get('DB_HOST', '127.0.0.1')
DB_CONN_MAX_AGE = os.environ.get('DB_CONN_MAX_AGE', 1800)
DB_MAX_CONNS = os.environ.get('DB_MAX_CONNS', 512)
DB_MIN_CONNS = os.environ.get('DB_MIN_CONNS', 20)
DB_RECYCLE = os.environ.get('DB_RECYCLE', 3600)
DB_CONNECT_TIMEOUT = os.environ.get('DB_RECYCLE', 1800)

REDIS_HOST = os.environ.get('REDIS_HOST', '127.0.0.1')
REDIS_PORT = os.environ.get('REDIS_PORT', '6379')
REDIS_PASSWORD = os.environ.get('REDIS_PASSWORD')
REDIS_DB_NUM = os.environ.get('REDIS_DB_NUM', '0')

# 扩大通道容量
CHANNEL_LAYERS_CAPACITY = int(os.environ.get('CHANNEL_LAYERS_CAPACITY', 5000))
"""注意，这里的channel通道容量的类型必须为int,不然会出现如下报错：
  File "/usr/local/lib/python3.11/dist-packages/channels/utils.py", line 57, in await_many_dispatch
2025-05-16T16:58:14.658293316Z     await task
2025-05-16T16:58:14.658300305Z TypeError: '<=' not supported between instances of 'str' and 'int'"""

LOGS_LEVEL = os.environ.get('LOGS_LEVEL', 'INFO')

GUACD_HOST = os.environ.get('GUACD_HOST', '192.168.1.153')
GUACD_PORT = os.environ.get('GUACD_PORT', 4822)

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": DB_NAME,
        "USER": DB_USER,
        "PASSWORD": DB_PASSWORD,
        "HOST": DB_HOST,
        "PORT": DB_PORT,
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            'connect_timeout': DB_CONNECT_TIMEOUT,  # 连接超时时间
        },
        'CONN_MAX_AGE': DB_CONN_MAX_AGE,
        'CONN_HEALTH_CHECKS': True,
        # 连接池配置
        'POOL': {
            'MAX_CONNS': DB_MAX_CONNS,  # 最大连接数
            'MIN_CONNS': DB_MIN_CONNS,  # 最小保持的连接数
            'RECYCLE': DB_RECYCLE,  # 连接回收时间(秒)
        }
    }
}

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB_NUM}",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": REDIS_PASSWORD
        }

    },
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB_NUM}",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": REDIS_PASSWORD
        }
    }
}
# 单独配置任务通道
REDIS_TASK_CHANNEL = "task_operations"

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [{
                'host': REDIS_HOST,
                'port': REDIS_PORT,
                'password': REDIS_PASSWORD,  # 添加你的 Redis 密码
                'db': REDIS_DB_NUM,  # 可选：指定数据库编号，默认是 0
            }],
            "capacity": CHANNEL_LAYERS_CAPACITY,  # 扩大通道容量至5000条
            "expiry": 30,  # 消息30秒后自动过期
            "group_expiry": 1800  # 组过期时间1小时
        },
    },
}

# 日志
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] [%(module)s.%(funcName)s] %(message)s',
        },
        'simple': {
            'format': '%(asctime)s [%(levelname)s] %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
            'stream': sys.stdout,
        },
    },
    'root': {
        'handlers': ['console'],
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': LOGS_LEVEL
        },
        'web': {
            'handlers': ['console'],
            'level': 'INFO'
        },
        'utils.aliyun.oss': {
            'handlers': ['console'],
            'level': 'INFO'
        }
    },
}

#####设置时区为中国时区#######
LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True
# USE_TZ = True
USE_TZ = False

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'static'  # 指定静态文件收集的目标目录

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# 设置访问白名单
CORS_ORIGIN_ALLOW_ALL = True
# 设置允许携带cookie
CORS_ALLOW_CREDENTIALS = True
# 设置默认允许请求头方法。
CORS_ALLOW_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
]

# session配置
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
# 设置session保存的位置对应的缓存配置项
SESSION_CACHE_ALIAS = 'session'
# 过期时间
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7

MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = 'media/'

